import { useNavigation, useRoute } from '@react-navigation/native';
import { useState } from 'react';
import { Platform } from 'react-native';
import { Product, Purchase, Subscription } from 'react-native-iap';
import Toast from 'react-native-toast-message';
import { useDispatch, useSelector } from 'react-redux';

// @ts-expect-error Route import path doesn't match the actual package structure
import { Route } from '@react-navigation/routers/src/types.tsx';
import { getStorageItem } from '@utils/storage.ts';
import { t } from 'i18next';

import map from './payment/config/map.json';
import { PaymentConfig as PaymentConfigType, usePayment, RestoreResult } from './payment/index';
import { paymentAPI } from '@/api/paymentAPI.ts';
// import {useNavigationRoute} from '../payHoohs/useNavigationRoute';
import { APP_NAME, DEVICE_ID, notificationKey, USER_ID } from '@/constants';
// import {FirebaseEvents} from '@/utils/firebaseEvents';
// import {notificationKey} from '@/utils/height';
import { setInfo } from '@/stores/slice/userSlice';
import { RootState } from '@/stores/store';
import { getUserMemberInfo, isAndroid } from '@/utils';
import { AdjustEventsUtil } from '@/utils/adjust';
import eventEmitter from '@/utils/eventManager';
import { isShowTestURL } from '@/utils/http';
import { showToast } from '@/utils/showToast';

// 项目业务中支付业务hooks（应用层）
export const useBusinessPayment = () => {
  const [isSubscribing, setIsSubscribing] = useState(false);
  const memberInfo = useSelector((state: RootState) => state.user.info);
  const isSubscribe = useSelector((state: RootState) => state.user.subscribe);
  const _navigation = useNavigation();
  // const {navigationToSubscribePage} = useNavigationRoute();
  const dispatch = useDispatch();

  const route = useRoute();
  const _routeName = route.name;

  // 校验订单支付状态轮询处理
  const handleVerifyPurchase = async (
    product: Product & Subscription,
    purchased: Purchase,
    orderId: number,
    googleProductCode: string,
    productCode: string,
    maxRetry = 10,
    retry = 0,
  ): Promise<boolean> => {
    console.log('准备开始轮询了');
    if (purchased.transactionId) {
      try {
        let transactionInfo: Payment.TransactionTrueOrFalse | Payment.TransactionsInfoAndroidResponse | undefined;

        console.log('start======================');
        console.log('orderId = ', orderId);
        console.log('end========================');

        if (Platform.OS === 'ios') {
          // 传递苹果交易的transactionId和订单id到后端进行订单状态查询
          transactionInfo = await paymentAPI.getTransactionsInfo(purchased.transactionId, orderId);
        }

        if (Platform.OS === 'android') {
          console.log('谷歌code = ', googleProductCode);
          console.log('真实code = ', productCode);
        }

        console.log('start======================');
        console.log('我来到了这里 = ', transactionInfo);
        console.log('end========================');

        if (!transactionInfo || !transactionInfo.data) {
          showToast.toastWarning('transactionInfo error');
          setIsSubscribing(false);

          return false;
        }

        // 打印业务异常
        if (transactionInfo.code !== 0) {
          showToast.toastWarning('transactionInfo error');
          setIsSubscribing(false);
          await finishTransaction(purchased);

          return false;
        }

        console.log('start======================');
        console.log('transactionInfo.status = ', transactionInfo.data.status);
        console.log('end========================');
        if (![0, 4].includes(transactionInfo.data.status)) {
          // 如果是安卓端，判断是不是应用内商品，如果是消耗品可以重复购买，需要传参数isConsumable
          const isConsumable = Platform.OS === 'android' && isInappProduct(product);
          console.log({ isConsumable });
          // TODO 购买credits应该允许重复购买，但对于永久订阅，应该不允许重复购买，不然涉及用户联系退费的隐藏问题，需要后端配合
          // 后端判断为支付成功，结束交易
          // android端支付成功，后端进行finish，前端不需要finish
          try {
            if (Platform.OS === 'ios') {
              await finishTransaction(purchased, isConsumable);
            }
          } catch (error) {
            console.error(error);
          }
          showToast.toastWarning('Purchase successfully, enjoy yourself!');

          // 根据交易的产品，上报不同的支付成功事件
          // 周支付成功
          if (purchased.productId.includes('weekly')) {
            AdjustEventsUtil.purchase_weekly();
          }
          // 月支付成功
          if (purchased.productId.includes('monthly')) {
            // AdjustEventsUtil.();
          }
          // 年支付成功
          if (purchased.productId.includes('yearly')) {
            AdjustEventsUtil.purchase_yearly();
          }
          // 永久支付成功
          if (purchased.productId.includes('lifetime')) {
            AdjustEventsUtil.purchase_lifetime();
          }

          showToast.toastSuccess('Purchase Successful');

          eventEmitter.emit(notificationKey.pay_success);

          // 前端更新会员信息
          getUserMemberInfo().then((res) => {
            dispatch(setInfo(res || null));
          });
          // 返回支付成功的标志
          setIsSubscribing(() => false);

          return true;
        } else {
          if (retry < maxRetry) {
            /** 重试查询交易结果 */
            // 正在查询，等待 1s
            console.log('当前重试次数：', retry);
            await new Promise((resolve) => setTimeout(resolve, 1000));
            return handleVerifyPurchase(
              product,
              purchased,
              orderId,
              googleProductCode,
              productCode,
              maxRetry,
              retry + 1,
            );
          } else {
            /** 超出最大重试次数 */
            // 前端认为此交易结束，完成交易，因有一些奇怪的transactionId和订单id一直保留，需要完成交易，不然可能下一次苹果弹框会不显示
            await finishTransaction(purchased);
            showToast.toastWarning('Purchase failed, please try again');
            setIsSubscribing(() => false);

            // 返回支付失败的标志
            return false;
          }
        }
      } catch (_error) {
        showToast.toastWarning('Purchase failed, please try again');
        setIsSubscribing(() => false);

        // 返回支付失败的标志
        return false;
      }
    }
    // 返回支付失败的标志
    return false;
  };

  // 配置公共hook usePayment的config
  const PaymentConfig: PaymentConfigType = {
    api: {
      ios: {
        createOrder: paymentAPI.create_payment_order,
        // Use type assertion to make it compatible
        verifyPurchase: (
          product: Product,
          purchase: Purchase,
          orderId: number,
          googleProductCode: string,
          productCode: string,
        ) =>
          // @ts-expect-error Type compatibility issue between Product and Product & Subscription
          handleVerifyPurchase(product, purchase, orderId, googleProductCode, productCode),
        restoreSubscription: (transactionReceipt: string): Promise<RestoreResult> => {
          // Type assertion to ensure compatibility
          return Promise.resolve({
            code: 0,
            msg: '',
            data: null,
            ...((paymentAPI.restoreSubscription(transactionReceipt) as unknown as Partial<RestoreResult>) || {}),
          });
        },
      },
      android: {
        createOrder: paymentAPI.create_payment_order_android,
        // Use type assertion to make it compatible
        verifyPurchase: (
          product: Product,
          purchase: Purchase,
          orderId: number,
          googleProductCode: string,
          productCode: string,
        ) =>
          // @ts-expect-error Type compatibility issue between Product and Product & Subscription
          handleVerifyPurchase(product, purchase, orderId, googleProductCode, productCode),
        restoreSubscription: (transactionReceipt: string): Promise<RestoreResult> => {
          // Type assertion to ensure compatibility
          return Promise.resolve({
            code: 0,
            msg: '',
            data: null,
            ...((paymentAPI.restoreSubscription(transactionReceipt) as unknown as Partial<RestoreResult>) || {}),
          });
        },
      },
    },
    options: {
      environment: isShowTestURL ? 'test' : 'prod',
      appName: APP_NAME,
    },
    events: {
      onCreateOrderSuccess: (res) => {
        // 业务异常
        if (res.code === 500003) {
          // 业务异常码为500003，为用户支付了创建了订单，不能重复创建，后端会隔半小时
          console.error('44900 error', res.msg);
          // ToastMessage.warning(t('toast.pay.frequent'));
          showToast.toastWarning('Frequent operations, please try again later');
          // 返回支付失败的标志
          return false;
        }
      },
      onCreateOrderFailed: (_error) => {
        showToast.toastWarning('Failed to create order');

        return false;
      },
      onRequestPurchaseSuccess: (_purchase) => {
        console.log('start======================');
        console.log('我支付成功了，但还未向后端请求权益');
        console.log('end========================');
      },

      onRequestPurchaseFailed: (_error) => {
        console.log('start======================');
        console.log('我支付失败了');
        console.log('end========================');
        showToast.toastWarning('Purchase failed, please try again');
        setIsSubscribing(false);
      },
      onRequestPurchaseCanceled: () => {
        console.log('start======================');
        console.log('我支付取消了');
        console.log('end========================');
        showToast.toastWarning('Purchase cancelled');
        setIsSubscribing(false);
      },
    },
  };

  // 使用公共支付hook
  const {
    isPaymentReady,
    isProcessing,
    handlePurchase,
    restorePurchases,
    getProductsFromStore,
    isInappProduct,
    finishTransaction,
    getProductPriceAndCurrency,
  } = usePayment(PaymentConfig);

  // Unused variables to suppress linter warnings
  // These variables are needed but not directly used, suppressing linter
  // isProcessing;
  // restorePurchases;

  // 获取全部产品列表,默认不传type，获取订阅产品；传2为获取单次付费产品
  const fetchAllPlanList = async (type?: string) => {
    try {
      const res = await getProductsFromStore(type ? [type] : []);
      return res;
    } catch (error) {
      console.error(error);
      return [];
    }
  };

  // 根据产品id数组过滤产品列表
  const filterPlanList = (productIds: string[], planList: Member.Product[]) => {
    const productMap = new Map<string, Member.Product>(
      planList.map((item) => [item.code, item]), // 将 product code 和 product 形成键值对存入 Map
    );

    const filteredPlanList = productIds
      .map((productId) => productMap.get(productId)) // 按照 productIds 顺序获取对应的产品
      .filter((item): item is Member.Product => item !== undefined); // 过滤掉不存在的产品

    return filteredPlanList;
  };

  // 点击支付按钮，弹起支付界面
  const handlePayment = async (
    selectedPlanCode: string,
    productCodeList: Array<Member.Product['code']>,
    prePayCallback?: () => void,
  ) => {
    if (!isPaymentReady) return false;

    if (!prePayCallback) {
      // 上报点击了按钮事件
      AdjustEventsUtil.checkout();
    } else {
      prePayCallback();
    }

    const storePayCode = getStorePayCode(selectedPlanCode);
    console.log('payCode = ', storePayCode);

    const skus = getSkus(productCodeList, selectedPlanCode);

    console.log('start======================');
    console.log('productCodeList = ', productCodeList);
    console.log('selectedPlanCode = ', selectedPlanCode);
    console.log('skus = ', skus);
    console.log('end========================');

    const products = await getProductsFromStore(skus);
    const product = products.find((item) => item.productId === storePayCode);
    const userId = getStorageItem(USER_ID);

    if (!product || !userId) {
      showToast.toastWarning('Purchase failed, please try again');
      return false;
    }

    setIsSubscribing(() => true);

    const result = await handlePurchase({
      product,
      skus,
      appAccountToken: getStorageItem(DEVICE_ID) || 'none-device-id',
      userId,
      env: __DEV__ ? 'test' : 'prod',
      businessProductCode: selectedPlanCode,
    });

    setIsSubscribing(() => false);

    return result?.success || false;
  };

  // 获取skus
  const getSkus = (productCodeList: string[], selectedPlanCode: string) => {
    if (isAndroid()) {
      const android = map.android as Record<string, string>;
      const storePayCode = getStorePayCode(selectedPlanCode);
      const skus = productCodeList
        .map((item) => android[item] ?? selectedPlanCode)
        .filter((itemCode) => itemCode === storePayCode);
      return skus;
    } else {
      return [selectedPlanCode];
    }
  };

  // 获取支付code
  const getStorePayCode = (selectedPlanCode: string) => {
    if (isAndroid()) {
      const android = map.android as Record<string, string>;
      const androidCode = android[selectedPlanCode] ?? selectedPlanCode;
      return androidCode;
    } else {
      return selectedPlanCode;
    }
  };

  // 获取权益请求个数
  const getPayAvailableCount = async () => {
    const res = await paymentAPI.getAvailableTimes();
    return res.data;
  };

  // 是否是会员的判断，如果不是会员则跳转订阅页面
  const jumpSubscribePageBeforePayment = async (_routeFrom?: string) => {
    // 必须是会员才可以单次付费
    if (![1, 2, 5].includes(memberInfo?.status ?? -99)) {
      Toast.show({
        type: 'tips',
        text1: t('toast.pay.subscribe.tips'),
        props: {
          _type: 'warning',
        },
      });
      return true;
    }
    return false;
  };

  // 跳转到购买Credit页面
  const jumpToBuyCreditPage = () => {
    // navigation.navigate('BuyCredit');
  };

  // 查询Credit剩余情况，不够则执行回调
  const handleNoAvailableTimes = async (needCreditNumber: number, callback?: () => Promise<void> | void) => {
    let isExistAvailableCount = 0;

    try {
      // 查询权益的剩余次数
      const availableCount = await getPayAvailableCount();

      isExistAvailableCount = availableCount.reduce(
        (pre: number, cur: { expired?: boolean; availableQuantity?: number }) => {
          if (!cur.expired) {
            return pre + (cur?.availableQuantity ?? 0);
          } else {
            return pre;
          }
        },
        0,
      );
      console.log({ availableCount }, needCreditNumber, isExistAvailableCount);
      // 如果不存在或者不够时，则需要付费
      if (!isExistAvailableCount || needCreditNumber > isExistAvailableCount) {
        if (callback) await callback();
        return true;
      }

      return false;
    } catch (error) {
      console.log(error);
      return false;
    }
  };

  // 用户是周期订阅会员的时候，当点击周期订阅会员时，提示用户已经是订阅会员，不用再次购买
  const handlePrePaySubscription = async (callback?: () => void) => {
    console.log({ memberInfo });

    if (memberInfo?.status && memberInfo.status === 1) {
      showToast.toastWarning('You are already a member, do not need to purchase again');
      if (callback) await callback();
      return true;
    }
    return false;
  };

  // 先判断用户是否是会员，如果是非会员，跳转到订阅页；如果是会员，跳转到Credit购买页
  const handleLackOfCredits = () => {
    // 如果是订阅会员，跳转到Credit购买页
    if (isSubscribe) {
      // 跳转到Credit购买页
      jumpToBuyCreditPage();
    }
  };

  const getProductSDKDetail = (productIdList: string[]) => {
    return getProductsFromStore(productIdList);
  };

  return {
    isPaymentReady,
    isSubscribing,
    fetchAllPlanList,
    filterPlanList,
    handlePayment,
    getPayAvailableCount,
    jumpSubscribePageBeforePayment,
    handleNoAvailableTimes,
    jumpToBuyCreditPage,
    handlePrePaySubscription,
    handleLackOfCredits,
    getProductSDKDetail,
    getPriceAndCurrency: getProductPriceAndCurrency,
  };
};
